import React, { useState, useEffect } from 'react';
import {
  addPopularSite,
  updatePopularSite,
  deletePopularSite,
  listPopularSite,
  PopularSiteVO,
} from '@/services/popularSite/api';
import { PlusOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';
import { Button, Modal, Form, Input, message, Popconfirm } from 'antd';
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import styles from './index.less';

const SiteCard: React.FC<{
  site: PopularSiteVO;
  index: number;
  moveCard: (dragIndex: number, hoverIndex: number) => void;
  onEdit: (site: PopularSiteVO) => void;
  onDelete: (id: string) => void;
}> = ({ site, index, moveCard, onEdit, onDelete }) => {
  const ref = React.useRef<HTMLDivElement>(null);
  const [{ isDragging }, drag] = useDrag({
    type: 'card',
    item: { index },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });

  const [, drop] = useDrop({
    accept: 'card',
    hover: (item: { index: number }, monitor) => {
      if (!ref.current) return;
      const dragIndex = item.index;
      const hoverIndex = index;
      if (dragIndex === hoverIndex) return;
      moveCard(dragIndex, hoverIndex);
      item.index = hoverIndex;
    },
  });

  drag(drop(ref));

  return (
    <div ref={ref} className={styles.siteCard} style={{ opacity: isDragging ? 0.5 : 1 }}>
      <div className={styles.cardActions}>
        <Button
          type="text"
          icon={<EditOutlined />}
          onClick={(e) => {
            e.stopPropagation();
            onEdit(site);
          }}
        />
        <Popconfirm
          title="确定要删除这个网站吗？"
          onConfirm={(e) => {
            e?.stopPropagation();
            onDelete(site.id);
          }}
          onCancel={(e) => e?.stopPropagation()}
        >
          <Button
            type="text"
            icon={<DeleteOutlined />}
            onClick={(e) => e.stopPropagation()}
          />
        </Popconfirm>
      </div>
      <a href={site.siteUrl} target="_blank" rel="noopener noreferrer">
        <div className={styles.siteContent}>
          <div className={styles.siteName}>{site.siteName}</div>
        </div>
      </a>
    </div>
  );
};
const CardContainer: React.FC<{children}> = ({children})=>{
  const [{canDrop,isOver},drop] = useDrop(()=>({
    accept : 'card',
    drop: ()=>({name: 'Conrainer'}),
    collect: (monitor)=>({
      isOver: monitor.isOver(),
      canDrop: monitor.canDrop(),
    })
  }))
  return (
    <div ref={drop} style={{
      width: '100%',
      height: '100%',
    }}>
      {children}
    </div>
  )
}
const PopularSite: React.FC = () => {
  const [sites, setSites] = useState<PopularSiteVO[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingSite, setEditingSite] = useState<PopularSiteVO | null>(null);
  const [form] = Form.useForm();
  const fetchSites = async () => {
    try {
      const data = await listPopularSite({});
      setSites(data.data);
    } catch (error) {
      message.error('获取常用网站失败');
    }
  };
  // 移除 ahooks 的 useLocalStorageState，使用原生 React 实现
  const [localSites, setLocalSites] = useState<PopularSiteVO[]>(() => {
    const storedValue = typeof window !== 'undefined' ? window.localStorage.getItem('popular-sites') : null;
    return storedValue ? JSON.parse(storedValue) : [];
  });

  useEffect(() => {
    fetchSites();
  }, []);

  // 新增 useEffect 监听 localSites 变化，更新 localStorage
  useEffect(() => {
    if (typeof window !== 'undefined') {
      window.localStorage.setItem('popular-sites', JSON.stringify(localSites));
    }
  }, [localSites]);

  const moveCard = (dragIndex: number, hoverIndex: number) => {
    const newSites = [...sites];
    const dragItem = newSites[dragIndex];
    newSites.splice(dragIndex, 1);
    newSites.splice(hoverIndex, 0, dragItem);
    setSites(newSites);
    setLocalSites(newSites);
  };



  const handleAdd = () => {
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      console.log(values);
      if (editingSite) {
        await updatePopularSite({ ...values, id: editingSite.id });
        message.success('更新成功');
      } else {
        await addPopularSite(values);
        message.success('添加成功');
      }
      setIsModalVisible(false);
      setEditingSite(null);
      fetchSites();
    } catch (error) {
      message.error(editingSite ? '更新失败' : '添加失败');
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <h2>常用网站</h2>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
          添加网站
        </Button>
      </div>

      <DndProvider backend={HTML5Backend}>

        <div className={styles.siteList}>
          <CardContainer>
            {sites.map((site, index) => (
              <SiteCard
                key={site.id}
                site={site}
                index={index}
                moveCard={moveCard}
                onEdit={(site) => {
                  setEditingSite(site);
                  form.setFieldsValue(site);
                  setIsModalVisible(true);
                }}
                onDelete={async (id) => {
                  try {
                    await deletePopularSite({ id });
                    message.success('删除成功');
                    fetchSites();
                  } catch (error) {
                    message.error('删除失败');
                  }
                }}
              />
            ))}
          </CardContainer>
        </div>
      </DndProvider>

      <Modal
        title={editingSite ? '编辑常用网站' : '添加常用网站'}
        visible={isModalVisible}
        onOk={handleSubmit}
        onCancel={() => {
          setIsModalVisible(false);
          setEditingSite(null);
        }}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="siteName"
            label="网站名称"
            rules={[{ required: true, message: '请输入网站名称' }]}
          >
            <Input placeholder="请输入网站名称" />
          </Form.Item>
          <Form.Item
            name="siteUrl"
            label="网站地址"
            rules={[{ required: true, message: '请输入网站地址' }]}
          >
            <Input placeholder="请输入网站地址" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default PopularSite;
